#include<stdio.h>
#include<fcntl.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<pthread.h>
#include<string.h>
#include<errno.h>

#define SYNC_PATH "test.txt"
//#define BLOCK_TIME 3000
void *read_func(void *arg);
void *write_func(void *arg);
pthread_mutex_t init = PTHREAD_MUTEX_INITIALIZER;
fd_set read_set;
int main() {
	pthread_t read_id,write_id;
	int read_ret,write_ret;
        write_ret = pthread_create(&write_id,NULL,write_func,NULL);
        if(write_ret!=0)
                printf("Can't create thread:%s\n",strerror(errno));
	read_ret = pthread_create(&read_id,NULL,read_func,NULL);
	if(read_ret!=0)
		printf("Can't create thread:%s\n",strerror(errno));
	printf("I'm main thread\n");
	pthread_join(write_id,NULL);

	pthread_join(read_id,NULL);
		
	exit(0);
}

void* read_func(void* arg) {
//	pthread_mutex_lock(&init);
	printf("I'm read thread\n");
	int fd = open(SYNC_PATH,O_RDONLY);
    if (fd < 0) {
    printf("In read thread, open failed.");
    }
	FD_ZERO(&read_set);
	FD_SET(fd,&read_set);
	char buffer[10];
	if(select(fd+1,&read_set,NULL,NULL,0))
	{
		if(FD_ISSET(fd,&read_set)){
			int bytes = read(fd,buffer,10);
			lseek(fd,10-bytes,SEEK_CUR);
			printf("read from file:%s\n",buffer);
			if(bytes>0)
                           return;
		}
	}
	close(fd);
//	pthread_mutex_unlock(&init);
	
}

void* write_func(void* arg) {
//	pthread_mutex_lock(&init);
	printf("I'm write thread\n");
	int fd = open(SYNC_PATH,O_CREAT|O_TRUNC|O_WRONLY,10705);
	printf("请输入内容,不超过十个字符:\n");
	char buffer[10];
	scanf("%s",buffer);
	write(fd,buffer,10);
	close(fd);
//	pthread_mutex_unlock(&init);
}	
